<script lang="ts" setup>
import { reactive, ref, watch, toRefs } from "vue"
// import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
import { ElTable, FormInstance, ElMessage } from "element-plus"
// 接口
import { getSettlement, updateSettlent, downLoadExcel } from "@/api/SZ/settlement"

import { usePagination } from "@/hooks/usePagination"
import { formatDateTime } from "@/utils"

// import { Search, Refresh } from "@element-plus/icons-vue"
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "dayNumber"
})
const DATA = reactive<any>({
  formData: { details: "" }
})
const { formData } = toRefs(DATA)
/**修改 */
const dialogVisible = ref(false)
const formRef = ref<FormInstance | null>(null)
const handleEdit = (row: any) => {
  dialogVisible.value = true
  formData.value = JSON.parse(JSON.stringify(row))
  console.log("row", row)
}
const resetForm = () => {
  formRef.value?.resetFields()
}
const handleCreate = () => {
  formRef.value?.validate((valid: any) => {
    if (valid) {
      console.log("submit!", formData.value)
      // 提交数据
      updateSettlent(formData.value)
        .then((res: any) => {
          if (res.code == 200) {
            ElMessage.success("修改成功")
            getList()
            // 关闭弹窗
            dialogVisible.value = false
          } else {
            ElMessage.error(res.message)
          }
        })
        .catch(() => {
          ElMessage.error("修改失败")
        })
    } else {
      console.log("error submit!!")
      return false
    }
  })
}
// ****************订单批量上传*******************************
import { getToken } from "@/utils/cache/cookies"
const uploadRef = ref<any>(null)
const upload = reactive({
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  headers: { token: getToken() },
  // 上传的地址
  url: "",
  //模板下载地址
  templateUrl: ""
})

//批量新增按钮点击
const submitAdd = () => {
  upload.open = true
  upload.title = "导入"
  upload.url = "api/table/balance/batchAdd"
  upload.templateUrl = "api/table/balance/down/downTemplate"
}

const updateInfo = ref<any>(null)
const updateSuccInfo = ref<boolean>(false)
const handleFileUploadProgress = () => {
  upload.isUploading = true
}
const handleSucc = (res: any) => {
  // loading.value = false
  console.log(res)
  if (res.code == 200) {
    getList()
    updateInfo.value = res
    updateSuccInfo.value = true
    upload.isUploading = false
    upload.open = false
    uploadRef.value.clearFiles()

    // ElMessage.success("成功！")
  } else {
    ElMessage.error(res.message)
  }
}
/** 提交上传文件 */
const submitFileForm = () => {
  uploadRef.value.submit()
}
// *********************订单上传结束*************************
// #endregion
// #region 查
const tableTotal = ref<number>()
const tableData = ref<any[]>([])
const getList = () => {
  getSettlement({
    page: paginationData.currentPage,
    size: paginationData.pageSize
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
      loading.value = false
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  shopId: "",
  manageName: ""
})
// const resetSearch = () => {
//   searchFormRef.value?.resetFields()
//   if (paginationData.currentPage === 1) {
//     getList()
//     console.log("重置")
//   }
//   paginationData.currentPage = 1
// }
// const handleSearch = () => {
//   if (paginationData.currentPage === 1) {
//     getList()
//     console.log("查询")
//   }
//   paginationData.currentPage = 1
// }
// #endregion
const columns = ref<any>([
  { prop: "dcId", label: "追创科技id" },
  { prop: "source", label: "订单来源" },
  { prop: "reId", label: "推荐人" },
  { prop: "superName", label: "上级名称" },
  { prop: "operator", label: "运营商" },
  { prop: "masterPackName", label: "主套餐名称" },
  { prop: "packName", label: "子套餐名称" },
  { prop: "czActivateTime", label: "出账激活时间", formatter: (row: any) => formatDateTime(row.czActivateTime) },
  { prop: "czState", label: "出账状态" },
  { prop: "orderState", label: "系统订单状态" },
  { prop: "orderCreate", label: "追创科技系统提单时间", formatter: (row: any) => formatDateTime(row.orderCreate) },
  { prop: "orderActive", label: "追创科技系统激活时间", formatter: (row: any) => formatDateTime(row.orderActive) },
  { prop: "sjjsType", label: "上级结佣类型" },
  { prop: "sjjsCaliber", label: "上级结算口径" },
  { prop: "sjjsSum", label: "上级结佣金额" },
  { prop: "sjjsTime", label: "上级结算时间", formatter: (row: any) => formatDateTime(row.sjjsTime) },
  { prop: "sjwjsReason", label: "上级未结算原因" },
  { prop: "sjjsBillNum", label: "账单编号" },
  { prop: "dpjsType", label: "店铺结佣类型" },
  { prop: "dpjsCaliber", label: "店铺结算口径" },
  { prop: "dpjsSum", label: "店铺结佣金额" },
  { prop: "dpjsTime", label: "店铺结算时间", formatter: (row: any) => formatDateTime(row.dpjsTime) },
  { prop: "dpwjsReason", label: "店铺未结算原因" },
  { prop: "dpjsYears", label: "店铺结算归属年月" },
  { prop: "dljsType", label: "代理结佣类型" },
  { prop: "dljsCaliber", label: "代理结算口径" },
  { prop: "dljsSum", label: "代理结佣金额" },
  { prop: "dljsTime", label: "代理结算时间", formatter: (row: any) => formatDateTime(row.dljsTime) },
  { prop: "dlwjsReason", label: "代理未结算原因" },
  { prop: "dljsYears", label: "代理结算归属年月" },
  { prop: "zjDepartment", label: "以部门为单位追加达量金额" },
  {
    prop: "zjDepartmentTime",
    label: "部门数据上传时间",
    formatter: (row: any) => formatDateTime(row.zjDepartmentTime)
  },
  { prop: "zjShop", label: "以店铺为单位追加达量金额" },
  { prop: "zjShopTime", label: "店铺数据上传时间", formatter: (row: any) => formatDateTime(row.zjShopTime) },
  { prop: "zjSubsidy", label: "追加推广补贴奖励" },
  { prop: "zjSubsidyTime", label: "推广补贴数据上传时间", formatter: (row: any) => formatDateTime(row.zjSubsidyTime) },
  { prop: "hfDcCompany", label: "追创科技系统公司话费支出" },
  { prop: "hfDcShop", label: "追创科技系统店铺话费支出" },
  { prop: "hfDc2Company", label: "追创科技2.0公司话费支出" },
  { prop: "hfDc2Shop", label: "追创科技2.0店铺话费支出" },
  { prop: "hfOffline", label: "店铺线下支出" },
  { prop: "hfTime", label: "数据上传时间", formatter: (row: any) => formatDateTime(row.hfTime) },
  { prop: "kfCompanyMoney", label: "公司承担扣罚金额" },
  { prop: "kfCompanyZq", label: "公司扣罚归属账期" },
  { prop: "kfShopMoney", label: "店铺承担扣罚金额" },
  { prop: "kfShopZq", label: "店铺扣罚归属账期" },
  { prop: "kfDlMoney", label: "代理承担扣罚金额" },
  { prop: "kfDlZq", label: "代理扣罚归属账期" },
  { prop: "zcRg", label: "人工支出" },
  { prop: "zcShop", label: "店铺营销费用" },
  { prop: "zcAverage", label: "店铺均摊" },
  { prop: "zcQt", label: "其他费用支出" },
  { prop: "createTime", label: "创建时间", formatter: (row: any) => formatDateTime(row.createTime) },
  { prop: "updateTime", label: "更新时间", formatter: (row: any) => formatDateTime(row.updateTime) }
])
/**下载 */
const submitDownDown = () => {
  loading.value = true
  downLoadExcel({})
    .then((res: any) => {
      console.log(res)
      if (res.data.code === 500) {
        ElMessage.error(res.data.message)
        return false
      }
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      // console.log(res)
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "结算表.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
    })
    .catch(() => {
      ElMessage.error("下载失败")
    })
    .finally(() => {
      loading.value = false
    })
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getList, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <!-- <el-form-item prop="shopId" label="店铺">
          <el-select v-model="searchData.shopId" clearable filterable placeholder="请选择">
            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item> -->
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加职位 -->
      <div class="middle-top">
        <div>
          <el-button style="vertical-align: top" class="ml-3" color="#626aef" icon="CirclePlus" @click="submitAdd">
            导入
          </el-button>
          <el-button style="vertical-align: top" class="ml-3" type="success" icon="Download" @click="submitDownDown">
            导出
          </el-button>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <template v-for="column in columns" :key="column.prop">
            <el-table-column :prop="column.prop" :label="column.label" :formatter="column.formatter" />
          </template>
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="scope">
              <el-button type="text" size="small" @click="() => handleEdit(scope.row)">修改</el-button>
              <!-- <el-button type="text" size="small" @click="() => handleDelete(scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <!-- 批量新增 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="600px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleSucc"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              :href="upload.templateUrl"
              Download
              >下载模板</el-link
            >
            <span style="margin-right: 10px" />
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--修改  -->
    <el-dialog v-model="dialogVisible" title="修改" @close="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" label-width="180px">
        <el-form-item label="店铺结佣金额" prop="dpjsSum" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.dpjsSum"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="代理结佣金额" prop="dljsSum" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.dljsSum"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="以部门为单位追加达量金额" prop="zjDepartment" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.zjDepartment"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="以店铺为单位追加达量金额" prop="zjShop" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.zjShop"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="店铺承担扣罚金额" prop="kfShopMoney" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.kfShopMoney"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="代理承担扣罚金额" prop="kfDlMoney" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.kfDlMoney"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="人工支出" prop="zcRg" label-width="180">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="formData.zcRg"
            placeholder="请输入数字类型"
            style="width: 220px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <!-- 导入数据统计 -->
    <el-dialog v-model="updateSuccInfo" title="数据统计" width="50%">
      <div class="pbox">
        <p>1.时间：{{ updateInfo.time }}</p>
        <p>2.成功：{{ updateInfo.data.success }}</p>
        <p>3.失败：{{ updateInfo.data.fail }}</p>
        <p>4.结果描述：{{ updateInfo.data.msg }}</p>
        <p v-if="updateInfo.data.time">5.用时：{{ updateInfo.data.time }}毫秒</p>
      </div>

      <template #footer>
        <el-button @click="updateSuccInfo = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
